package com.android.djlmapp.activity.my.set;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.HomeActivity;
import com.android.djlmapp.activity.login.LoginActivity;
import com.android.djlmapp.adapter.my.MyBaseRecyclerViewAdapter;
import com.android.djlmapp.adapter.my.MyPwdRecyclerviewAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.MyUsualyDialog;
import com.android.djlmapp.listener.LocationCallBack;
import com.android.djlmapp.model.home.LocationInfo;
import com.android.djlmapp.model.home.LoginInfo;
import com.android.djlmapp.model.my.ListDataSave;
import com.android.djlmapp.model.my.People;
import com.android.djlmapp.network.ConnectivityType;
import com.android.djlmapp.network.NetWorkStateManager;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.login.OnceLocationTools;
import com.android.djlmapp.tools.login.PhoneUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ChangeAccountActivity extends BaseActivity {
    public static final String TAG = "djlm-my: ";
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.rec_account)
    RecyclerView recAccount;
    @BindView(R.id.my_new_one)
    RelativeLayout myNewOne;

    private Context mContext;
    List<String> mDataPwd;
    String[] stringArray = null;
    String[] stringArrayPwd = null;
    private Unbinder mUnbinder;
    private int pwdLoc = -1;

    private double latitude;
    private double longitude;
    private String user_name = "";
    private String user_password = "";
    private String phone_os = "";
    private String phone_type = "";
    private String phone_brand = "";
    private String phone_imei = "";
    private String phone_gps = "";
    private String Network = "";
    private String Phone_num = "";
    private String Push_id = "";
    private String version = "";
    private NetWorkStateManager manager;
    private int type = 0; // 第一次登录
    private boolean isLoginTo = false; //防止获取不到位置重复登录
    private MyUsualyDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_account);
        mContext = getActivity();
        mUnbinder = ButterKnife.bind(this);

        initData();
        initView();
    }

    @Override
    protected void initData() {
        homeIvReadpoint.setVisibility(View.GONE);
        topNotes.setVisibility(View.GONE);
        tvName.setText("账号切换");

        ListDataSave SpdataSave = new ListDataSave(this, "LoginSp");
        List<People> classTests = SpdataSave.getDataList("login");
        Log.i(TAG, ""+classTests.size());

        if (classTests.size() > 0) {
            //取最后三个
            if (classTests.size() >= 3) {

                stringArray = new String[3];
                stringArrayPwd = new String[3];

                for (int i = 0; i < 3; i++) {
                    stringArray[i] =
                            classTests.get(classTests.size() - (1 + i)).getName();
                    stringArrayPwd[i] =
                            classTests.get(classTests.size() - (1 + i)).getPwd();
                }
            } else {
                stringArray = new String[classTests.size()];
                stringArrayPwd = new String[classTests.size()];

                for (int i = 0; i < classTests.size(); i++) {
                    stringArray[i] =
                            classTests.get(classTests.size() - (1 + i)).getName();
                    stringArrayPwd[i] =
                            classTests.get(classTests.size() - (1 + i)).getPwd();
                }
            }
            mDataPwd = Arrays.asList(stringArray);
            Log.i(TAG, "mDataPwd"+mDataPwd.toString());
            Log.i(TAG, "stringArrayPwd"+stringArrayPwd.toString());
        }

    }

    @Override
    protected void initView() {
        if(stringArray != null){
            MyPwdRecyclerviewAdapter myRecyclerviewAdapter = new MyPwdRecyclerviewAdapter(mDataPwd, getActivity(), R.layout.my_cp_item);
            recAccount.setAdapter(myRecyclerviewAdapter);
            recAccount.setLayoutManager(new LinearLayoutManager(getActivity()));

            myRecyclerviewAdapter.setOnItemClickListener(new MyBaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    //此处进行监听事件的业务处理
                    if(! UserInfoUtils.getUserInfoUtilsInstance().getUserName().equals((mDataPwd.get(position)))){
                        changeAccount(position);
                    }
                }
            });
        }

    }


    @OnClick({R.id.ll_top_back, R.id.my_new_one})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;
            case R.id.my_new_one:
                startActivity(new Intent(mContext, LoginActivity.class)
                        .putExtra("cp", "2"));
                break;
        }
    }

    private void changeAccount(int pwdLoc){
        this.pwdLoc = pwdLoc;
        type = 1; // 第一次登陆
        isLoginTo = false;

        user_name = stringArray[pwdLoc];
        user_password = stringArrayPwd[pwdLoc];
        ChangeAccountActivityPermissionsDispatcher.openCameraWithCheck(this);

    }
    @NeedsPermission({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void openCamera() {
        // 获取手机信息
        Log.e("项目异常", "openCamera权限: =================");
        //等待
        dialog = new MyUsualyDialog(getActivity(), R.layout.login_waiting);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        getPhoneInfo();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ChangeAccountActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface mdialog, int which) {
                        request.cancel();

                        if(dialog != null){
                            dialog.dismiss();
                            dialog = null;
                        }
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获手机信息,定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void denied() {
        Log.e("权限", "------denied------");
        // 获取手机信息
        if(dialog != null){
            dialog.dismiss();
            dialog = null;
            ToastUtils.showLongToastSafe(mContext, "切换账号失败,未获取到定位和手机状态权限!");
        }
    }

    @OnNeverAskAgain({Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void askAgain() {
        // 获取手机信息
        Log.e("项目异常", "askAgain权限: =================");

        if(dialog != null){
            dialog.dismiss();
            dialog = null;
            ToastUtils.showLongToastSafe(mContext, "切换账号失败,未获取到定位和手机状态权限!");
        }
    }

    /**
     * 获取手机设备信息
     */
    @SuppressLint("MissingPermission")
    private void getPhoneInfo() {
        //极光推送唯一码
        Push_id = MyApplication.getInstance().getRegistrationId();
        if (Push_id == null) {
            Push_id = "";
        }
        Log.i("推送id", "getPhoneInfo: " + Push_id);
        //手机系统
        phone_os = Build.VERSION.RELEASE;
        //手机型号
        phone_type = Build.MODEL;
        //手机品牌
        phone_brand = Build.MANUFACTURER + "";
        //手机串码
        PhoneUtils phoneUtils = new PhoneUtils(this);
        phone_imei = phoneUtils.getImsi(this) + "";
        //获取手机号码
        TelephonyManager tm = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
        Phone_num = tm.getLine1Number() + "";
        manager = NetWorkStateManager.getInstance(getApplicationContext());
        //获取一次网络状态
        ConnectivityType connectedType = manager.getNetWorkState();
        Network = connectedType.getType();
        //实时获取网络状态

        getLocationPrem();
    }


    private void getLocationPrem() {

        try {
            OnceLocationTools locationTools = new OnceLocationTools(this, new LocationCallBack() {
                @Override
                public void successGetLocation(LocationInfo info) {
                    Log.e("坐标获取", info.getLatitude() + "---" + info.getLongitude());
                    latitude = info.getLatitude();
                    longitude = info.getLongitude();
                    phone_gps = latitude + ":" + longitude;
                    loginTo();
                }

                @Override
                public void error(String error) {
                    phone_gps = 0.0 + ":" + 0.0;
                    if (!isLoginTo) {
                        isLoginTo = true;  // 第一次进入就改变状态,防止再次进入,在点击的时候重置状态
                        loginTo();
                    }
                }
            });
            locationTools.startLocation();//开始定位
        } catch (NullPointerException ex) {
            phone_gps = 0.0 + ":" + 0.0;
            loginTo();
        }
    }


    private void loginTo() {
        UserInfoUtils.getUserInfoUtilsInstance().setToken("");

        MyApplication.getInstance().getHttpTools().login(Network, Phone_num, Push_id,
                phone_brand, phone_gps, phone_imei, phone_os, phone_type, type + "",
                user_name, user_password, mStringCallback);
    }

    private StringCallback mStringCallback = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            try {
                String body = response.body();
                Gson gson = new Gson();
                final LoginInfo loginInfo = gson.fromJson(body, LoginInfo.class);
                if (loginInfo != null) {
                    int code = loginInfo.getCode();
                    final String token = loginInfo.getToken();
                    if (code < 1000) {
                        LoginInfo.UserInfo user_info = loginInfo.getUser_info();
                        MyApplication.getInstance().setJPushInit();
                        // 保存用户信息
                        saveUserInfo(token, user_info);

                        Intent intent = new Intent(mContext,
                                HomeActivity.class);

                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                                | Intent.FLAG_ACTIVITY_NEW_TASK);

                        startActivity(intent);
                        finish();
                    } else {
//                        ToastUtils.showShortToast(mContext, loginInfo.getMsg());
                        if(pwdLoc > 0){
                            startActivity(new Intent(mContext, LoginActivity.class)
                                    .putExtra("mUserName", ""+stringArray[pwdLoc])
                                    .putExtra("mPwd", ""+ stringArrayPwd[pwdLoc])
                                    .putExtra("cp", "1"));
                        }
                    }
                }
            } catch (Exception e) {
                Log.e("项目异常", "------Exception------" + e);
                ToastUtils.showShortToast(mContext, "数据解析异常");
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            Log.e("登录结果", "-----onError------" + response.body());
            ToastUtils.showShortToast(mContext, "网络或服务器错误");
        }

        @Override
        public void onFinish() {
            super.onFinish();
            if (dialog != null) {
                dialog.dismiss();
                dialog = null;
            }
        }
    };

    private void saveUserInfo(String token, LoginInfo.UserInfo user_info) {
        // 登陆成功后存储状态，做为引导页的判断
        UserInfoUtils userInfoUtils = UserInfoUtils.getUserInfoUtilsInstance();

        userInfoUtils.setIsLog(true);// 是否登录
        userInfoUtils.setToken(token); //保存token
//        PrefReadCardTools.setBoolean(LoginActivity.this, "isLog", true); // 是否登录

        // 保存用户登录信息
        userInfoUtils.setPwd(user_password); // 登录密码
        userInfoUtils.setNetWork(Network);
        userInfoUtils.setPhoneNum(Phone_num);
        userInfoUtils.setPushId(Push_id);
        userInfoUtils.setPhoneBrand(phone_brand);
        userInfoUtils.setPhoneGps(phone_gps);
        userInfoUtils.setPhoneImei(phone_imei);
        userInfoUtils.setPhoneOs(phone_os);
        userInfoUtils.setPhoneType(phone_type);

        // 美恰客服需要
        userInfoUtils.setAgent(user_info.getUser_agent());
        userInfoUtils.setFaddress(user_info.getAddress());
        userInfoUtils.setMobile(user_info.getTel());
        userInfoUtils.setUserName(user_info.getName());

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }
}
